import React, { Component } from 'react'
import { base, toast, createPage } from 'nc-lightapp-front'
import initTemplate from './initTemplate'
import './index.less'
import requestApi from './requestApi'
import HighSpeedPhotoUtil from './HighSpeedPhoto/HighSpeedPhotoUtil'
import { CREATE_PAGE, TRANSFER_TABLE, PARENT_PAGE } from './constant'
import afterEvent  from './events/afterEvent';
import _ from 'lodash-es'

const elementContainerId = 'upload-invoice-' + CREATE_PAGE.pagecode

class UploadInvoice extends Component {
  uploadFileMaxCount = 0; //上传发票限制数
  invoiceList = []; //当前展示的发票列表数据 [{head: {head: {}}, body:{body: {}}}]  body是可选的
  changeKeys = {}; //"pk_erminvoice": []
  //固定按钮配置
  buttonData = {
      invoiceScan: {
          title: '201103INUP-0002',
          area: 'bottom',
      },
      invoiceUpload: {
          title: '201103INUP-0003',
          area: 'bottom',
      },
  }

  constructor (props) {
    super(props)
    this.state = {
      isTransferDisabled: true,
      editableItems: [],  //表体可编辑字段
      flag: false,
    }
    this.cashe = {}
    initTemplate.call(this, props)
  }

  componentWillUnmount() {
    //卸载组件清空数据,否则transferTable内部会有缓存
    this.props.transferTable.setTransferTableValue(TRANSFER_TABLE.headTableId, TRANSFER_TABLE.bodyTableId, [], TRANSFER_TABLE.headTablePk, TRANSFER_TABLE.bodyTablePk)
  }

  handleTransferTable (data) {
    const dataList = data.data || []
    const noFilter = data.filter || false
    dataList.forEach(item => {
      if(!item.body) {
        item.body = {}
        item.body.body = {rows: [], areacode: 'body'}
      }
    })
    // rows
    const preData = JSON.parse(JSON.stringify(this.cashe.preData || []))
    let headRows = JSON.parse(JSON.stringify(preData))

    if(noFilter) {
        const { transferTable } = this.props
        headRows = dataList
        transferTable.setTransferTableValue(TRANSFER_TABLE.headTableId, TRANSFER_TABLE.bodyTableId, headRows, TRANSFER_TABLE.headTablePk, TRANSFER_TABLE.bodyTablePk)
    } else {
            // 过滤 发票类型+发票代码+发票号码 相同的条目
            let keysSet = []
            preData.forEach(item => {
              const key = (item.head.head.rows[0].values.fpdm.value) + (item.head.head.rows[0].values.fphm.value) + (item.head.head.rows[0].values.fplxpk.value)
              keysSet.push(key)
            })

            dataList.forEach(item => {
              const key = (item.head.head.rows[0].values.fpdm.value) + (item.head.head.rows[0].values.fphm.value) + (item.head.head.rows[0].values.fplxpk.value);
              if( keysSet.indexOf(key) < 0 ) {
                headRows.push(item)
              } else {
                  toast({ content: '已过滤相同发票', color: 'danger' })
              }
            })

            const { transferTable } = this.props
            this.cashe = {
              // pageid,
              preData: headRows
            }
            transferTable.setTransferTableValue(TRANSFER_TABLE.headTableId, TRANSFER_TABLE.bodyTableId, headRows, TRANSFER_TABLE.headTablePk, TRANSFER_TABLE.bodyTablePk)
    }

  }

  onUploadChange (info) {
      if (info.file.status !== 'done' || info.event) return
      if (info.file.response.success !== true) {
        toast({ content: info.file.response.error.message, color: 'danger' })
        return
      }

      if( info.file.response.data[0] ) {
        const verifyFpMsg = info.file.response.data[0].userjson && JSON.parse(info.file.response.data[0].userjson).verifyFpMsg
        verifyFpMsg && toast({ content: verifyFpMsg, color: 'danger' })
      }

      try {
        this.handleInvoiceBodyData(info.file.response.data)
        this.handleTransferTable(info.file.response)
      } catch (err) {
        console.error(err)
        toast({ content: '数据格式错误', color: 'danger' })
      }
  }

  handleInvoiceBodyData(list=[]) {
    //
    list.forEach(item => {
      if(item.head.head.rows[0].values.inspectstatus) {
        if(item.body) {
          item.body.body.rows.forEach(row => {
            row.values.inspectstatus = item.head.head.rows[0].values.inspectstatus
          })
        }
      }
    })
  }

    //删除票据信息
    deleteTableData = (delKeys=[]) => {
        const preData = JSON.parse(JSON.stringify(this.cashe.preData));
        const filterRows = [];
        preData.forEach(item => {
            const kk = item.head.head.rows[0].values.pk_erminvoice.value
            if(!delKeys.includes(kk)) {
                filterRows.push(item)
            }
        })

        this.cashe = {
            ...this.cashe,
            preData: filterRows
        };

        this.props.transferTable.setTransferTableValue(TRANSFER_TABLE.headTableId, TRANSFER_TABLE.bodyTableId, filterRows, TRANSFER_TABLE.headTablePk, TRANSFER_TABLE.bodyTablePk);
        this.props.transferTable.cancelRowsChecked('head', delKeys)  //删除之后已选不显示
        this.setState({
          isTransferDisabled: !this.props.transferTable.getTransferTableAllSelectedId(elementContainerId)[TRANSFER_TABLE.headTableId].head.length
        })
    }

    handleDeleteRows = () => {
        const keys = this.props.transferTable.getTransferTableAllSelectedId(elementContainerId)[TRANSFER_TABLE.headTableId].head
        const multiLang = this.props.parentProps.MutiInit.getIntl(2011)
        if (keys && keys.length === 0) {
            toast({content: multiLang && multiLang.get('201101BXLX-0003'), color:'danger'})
            return
        }
        this.deleteTableData(keys)
    }

    //选中逻辑 -> 不可单独选择子表，只能全选
  onTransferCheckedChange (flag, record) {
    //非全选
    // if(!Array.isArray(record)) {
      // const key = record.pk_erminvoice.value
      // let child_key = record.pk_erminvoice_b && record.pk_erminvoice_b.value
      // //勾选子表 -> 全选
      // let body_keys = []
      // this.cashe.preData.forEach(item => {
      //     if(item.head.head.rows[0].values.pk_erminvoice.value === key) {
      //         if(item.body) {
      //             body_keys = item.body.body.rows.map(_itm => {
      //               if(_itm.values.pk_erminvoice_b.value !== child_key) return _itm.values.pk_erminvoice_b.value }
      //             )
      //         }
      //     }
      // })
      //只勾选兄弟元素，否则计算错误
      // body_keys = body_keys.filter(itm => itm && itm)
      // if(body_keys.length > 0 && flag) {
      //     this.props.transferTable.setTheCheckRows('head', body_keys)
      // }
      // if(!flag) {
      //     this.props.transferTable.cancelRowsChecked('head', [key])
      // }
    // }
    this.setState({
      isTransferDisabled: !this.props.transferTable.getTransferTableAllSelectedId(elementContainerId)[TRANSFER_TABLE.headTableId].head.length
    })
  }

  async onScanButtonClick () {
    const props = this.props.parentProps

    let imgList = [] // 图片
    // 0. 校验
    const reg = await new Promise((resolve) => {
      HighSpeedPhotoUtil.checkScanPlugin((reg) => {
        resolve(reg)
      })
    })

    // 1.1 好使
    if (reg === 'ok') {
      // 1.2 图片
      imgList = await new Promise((resolve) => {
        HighSpeedPhotoUtil.startScan(async (data) => {
          const list = await HighSpeedPhotoUtil.getScanResultByIdList(data)
          resolve(list)
        })
      })
    }

    // 2. 上传识别
    imgList.forEach((v) => {
      v.pagecode = CREATE_PAGE.pagecode
      v.tepmid = this.props.meta.getMeta().pageid
      v.pk_org = props.form.getFormItemsValue('head', 'pk_org').value
      v.pk_psndoc = props.form.getFormItemsValue('head', 'jkbxr').value
      v.fileBase64Str = v.imgData
      v.fileName = v.name
      v.imgData = undefined
    })
    HighSpeedPhotoUtil.uploadFile(imgList, (data) => {
      data.forEach(item => {
        this.handleTransferTable(item)
      })
    })
  }

  onReimbursementButtonClick () {
    const keys = this.props.transferTable.getTransferTableAllSelectedId(elementContainerId)[TRANSFER_TABLE.headTableId].head
    const multiLang = this.props.parentProps.MutiInit.getIntl(2011)
    if (keys && keys.length === 0) {
        toast({content: multiLang && multiLang.get('201101BXLX-0003'), color:'danger'})
        return
    }
    const props = this.props.parentProps
    const { hide } = this.props
    const bodys = PARENT_PAGE.bodys
    let hideBody, i
    if ((i = props.form.getFormItemsValue('head', ['iscostshare'])) && (i = i[0].value) && i === true) {
      hideBody = ''
    } else {
      hideBody = 'er_cshare_detail'
    }
    const pagecode = props.getSearchParam('p')
    const billdata = props.createExtCardData(pagecode, 'head', bodys.filter(item => {
      return item !== hideBody
    }))
    const tablecode = window.invoiceListQueryParam && window.invoiceListQueryParam.tablecode;
    const uj = {
      pagecode,
      tradetype: props.form.getFormItemsValue('head', 'pk_tradetypeid').value,
      appcode: props.getSearchParam('c'),
      templateid: props.meta.getMeta().pageid,
      tablecode
    }
    billdata.userjson = JSON.stringify({
      ...uj,
      invoiceDataList: this.getTableValue2()
    })
    billdata.templetid = props.meta.getMeta().pageid

    requestApi.doReimbursement({
      data: billdata,
      success: (data) => {
        const userjson_parse = JSON.parse(data.userjson) || {}

        window.presetVar.invoiceToBx = userjson_parse.invoiceToBx
        window.presetVar.bxToInvoice = userjson_parse.bxToInvoice

        if(userjson_parse.errorInfoList && Array.isArray(userjson_parse.errorInfoList)) {
          if(userjson_parse.errorInfoList.length > 0) toast({content: userjson_parse.errorInfoList.reduce((acc, cur) => acc + cur + '\\n', ''), color:'danger'})
        }
        props.form.setAllFormValue({ [PARENT_PAGE.heads[0]]: data.head[PARENT_PAGE.heads[0]] })
        Object.keys(data.bodys).forEach((item) => {
          const newitemdata = data.bodys[item]
          if (newitemdata && newitemdata.rows) {
            const rows = []
            for (let i = 0; i < newitemdata.rows.length; i++) {
              // if (newitemdata.rows[i].values && newitemdata.rows[i].values.tablecode && newitemdata.rows[i].values.tablecode.value == item) {
              if (newitemdata.rows[i].values) {
                rows[rows.length] = newitemdata.rows[i]
              }
            }
            newitemdata.rows = rows
          }

          newitemdata && props.cardTable.setTableData(item, newitemdata, null, false)
        })
        hide()
      },
      error: (data) => {
        toast({ content: data.message, color: 'danger' })
      }
    })
  }

  //数据改造  主子表结构

  getTableValue2 () {
    const tableData = this.props.transferTable.getTransferTableValue()
    const cacheList = JSON.parse(JSON.stringify(this.cashe.preData))
    //返回数据
    const ret = []

    //选中的主表pk list
    const selectedMainKeysList = Object.keys(tableData.head.selected.selectedData.masterSelData)
    console.log('selected main keys:', selectedMainKeysList)
    cacheList.forEach(item  => {
      const pk_erminvoice = item.head.head.rows[0].values.pk_erminvoice.value
      if( selectedMainKeysList.indexOf(pk_erminvoice) > -1 ) {

        const headRowsValues = item.head.head.rows[0].values
        delete headRowsValues.key
        delete headRowsValues.rowIndex
        delete headRowsValues.headKey

        let changeKeys = this.changeKeys[pk_erminvoice]

        item.body.body.rows.forEach(itm => {
          delete itm.values.key
          delete itm.values.rowIndex
          delete itm.values.parentRowId
        })
        let invoice = JSON.parse(item.userjson);
        if (invoice.changeKeys || _.isEmpty(invoice)) {
            invoice = item.head.userjson
        } else {
            invoice = item.userjson
        }
        ret.push({
            head: {
                model: { ...item.head.head, areacode: 'head', areaType: 'table' },
                userjson: invoice
            },
            userjson: JSON.stringify({ changeKeys }),
            body: { model: { ...item.body.body, areacode: 'body', areaType: 'table' } }
        });
      }
    })
    return ret
  }

  onSaveToWallet () {
    const keys = this.props.transferTable.getTransferTableAllSelectedId(elementContainerId)[TRANSFER_TABLE.headTableId].head
    const multiLang = this.props.parentProps.MutiInit.getIntl(2011)
    if (keys && keys.length === 0) {
        toast({content: multiLang && multiLang.get('201101BXLX-0003'), color:'danger'})
        return
    }
    const { hide } = this.props
    const data = {
      pagecode: CREATE_PAGE.pagecode,
      tepmid: this.props.meta.getMeta().pageid,
      billdata: this.getTableValue2()
    }

    requestApi.saveToWallet({
      data,
      success: (res) => {
        //modified 存在查验失败的情况,不再关闭界面，再重新渲染查验失败的发票
        if(res && res.errorInfoList && res.errorInfoList.length > 0) {
          if(Array.isArray(res.errorInfoList)) {
            if(res.errorInfoList.length > 0) toast({content: res.errorInfoList.reduce((acc, cur) => acc + cur + '\\n', ''), color:'danger'})
            //todo 重新渲染查验失败的发票
            const list = { data:[], filter: true }
            if(res.errordata && res.errordata.length > 0) {
              list.data = [...res.errordata]
              this.cashe.preData = [...res.errordata] //错误信息清空之前缓存
              this.handleTransferTable(list)
            }
          }
          //取消勾选
          const tableData = this.props.transferTable.getTransferTableValue()
          //选中的主表pk list
          const selectedMainKeysList = Object.keys(tableData.head.selected.selectedData.masterSelData)
          this.props.transferTable.cancelRowsChecked(
            TRANSFER_TABLE.headTableId,
            selectedMainKeysList
          );
          return
        }
        hide()
      }
    })
  }

  uploadBefore = (file) => {
    this.uploadFileMaxCount += 1
    if(this.uploadFileMaxCount > 9) {
      toast({ content: '单次上传不能超过9张!', color: 'danger' })
      return false
    }

    if (file.size > 10 * 1024 * 1024) {
      toast({content: `单次上传不能超过10M`, color: 'info'})
      return false;
    }

    if (file.type.indexOf('image/') === 0) {
      if (file.size < 500 * 1024) return true

      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        let img = new Image();
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        img.onload = function () {
          // 图片原始尺寸
          let originWidth = this.width;
          let originHeight = this.height;
          // 目标尺寸
          let targetWidth = originWidth;
          let targetHeight = originHeight;
          // 最大尺寸限制
          let maxWidth = 1280;
          let maxHeight = 1280;
          if (originWidth > maxWidth || originHeight > maxHeight) {
            // 更宽，按照宽度限定尺寸
            if (originWidth / originHeight > maxWidth / maxHeight) {
              targetWidth = maxWidth;
              targetHeight = Math.round(maxWidth * (originHeight / originWidth));
            } else {
              targetHeight = maxHeight;
              targetWidth = Math.round(maxHeight * (originWidth / originHeight));
            }
          }

          // canvas对图片进行缩放
          canvas.width = targetWidth;
          canvas.height = targetHeight;
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight);
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight);
          // canvas转为blob并上传
          canvas.toBlob(function (blob) {
            resolve(new File([blob], file.name, { type: file.type }));
            reader = null
            img = null
            context = null
            canvas = null
          }, file.type, file.type === 'image/jpeg' || file.type === 'image/webp' ? 0.98 : 1);
        };

        // 文件base64化，以便获知图片原始尺寸
        reader.onload = function(e) {
          img.src = e.target.result;
        };
        reader.readAsDataURL(file);
      })
    }
    return true
  }

  selectArea () {
    // return null
    const { NCUpload, NCButton } = base
    const props = this.props.parentProps
    const data = {
      pagecode: CREATE_PAGE.pagecode,
      tepmid: this.props.meta.getMeta().pageid,
      pk_org: props.form.getFormItemsValue('head', 'pk_org').value,
      pk_psndoc: props.form.getFormItemsValue('head', 'jkbxr').value
    }
    const multiLang = props.MutiInit.getIntl(2011) // this.moduleId

    // debugger
    return (
      <div>
        <NCButton onClick={this.handleDeleteRows.bind(this)}>{multiLang && multiLang.get('201103INUP-0001')}</NCButton>
        {this.buttonData.invoiceScan.area === 'bottom' ?
          <NCButton onClick={this.onScanButtonClick.bind(this)}>{multiLang && multiLang.get(this.buttonData.invoiceScan.title)}</NCButton>
          :
          null
        }
        <NCUpload style={{ marginLeft: 10 }}
                  name='file'
                  showUploadList={false}
                  action={TRANSFER_TABLE.uploadUrl}
                  data={data}
                  onChange={this.onUploadChange.bind(this)}
                  accept='.gif,.jpg,.png,.pdf,.ofd'
                  multiple
                  beforeUpload={this.uploadBefore.bind(this)}
        >
        { this.buttonData.invoiceUpload.area === 'bottom' ?
          <NCButton onClick={()=> {this.uploadFileMaxCount = 0}}>{ multiLang && multiLang.get(this.buttonData.invoiceUpload.title)}</NCButton>
          :
          null
        }
        </NCUpload>
        <NCButton
          onClick={this.onSaveToWallet.bind(this)}
          // shape='border'
          className='main-button button-component large-btn'
          disabled={this.state.isTransferDisabled}
          style={{ marginLeft: 16 }}
        >
          {multiLang&&multiLang.get('201103INUP-0004')}
        </NCButton>
        <NCButton
          onClick={this.onReimbursementButtonClick.bind(this)}
          // shape='border'
          className='main-button button-component large-btn'
          disabled={this.state.isTransferDisabled}
          style={{ marginLeft: 16 }}
        >
          {multiLang&&multiLang.get('201103INUP-0005')}
        </NCButton>
      </div>
    )
  }

  render () {
    const { transferTable } = this.props
    const { createTransferTable } = transferTable
    const { editableItems } = this.state;
    // const multiLang = this.props.MutiInit.getIntl(2011) // this.moduleId
    return (
      <div className='container'>
        <div className='upload-invoice-wrapper__2011' id={elementContainerId}>
          {createTransferTable({
            dataSource: elementContainerId,
            comType: 'hasCheckBox',
            editStatus: true,
            headTableId: TRANSFER_TABLE.headTableId, // 表格组件id
            bodyTableId: TRANSFER_TABLE.bodyTableId,
            showGenerateBtn: false, // 隐藏右下角按钮
            containerSelector: `#${elementContainerId}`, // 容器的选择器 必须唯一,用于设置底部已选区域宽度
            selectArea: this.selectArea.bind(this),
            editableItem: editableItems,
            onCheckedChange: this.onTransferCheckedChange.bind(this),
            afterEvent: afterEvent.bind(this)
          })}
        </div>
      </div>
    )
  }
}

export default createPage({
  billinfo: {
    billtype: CREATE_PAGE.billtype,
    headcode: CREATE_PAGE.headcode,
    pagecode: CREATE_PAGE.pagecode
  }
})(UploadInvoice)
